在Laravel 5.6 Auth 使用 reCAPTCHA

Author Avatar
Sakamoto 9月 29, 2018

使用 anhskohbo/no-captcha

Installation

1
composer require anhskohbo/no-captcha

Setup

app/config/app.php 新增

  • providers 新增

    1
    Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,
  • aliases 新增

    1
    'NoCaptcha' => Anhskohbo\NoCaptcha\Facades\NoCaptcha::class,
  • Publish the config file

    1
    php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"

Configuration

新增 NOCAPTCHA_SECRET and NOCAPTCHA_SITEKEY.env

1
2
NOCAPTCHA_SECRET=secret-key
NOCAPTCHA_SITEKEY=site-key

記得在 Google recaptcha 註冊

使用

  • login.blade.php 添加

    1
    <div class="g-recaptcha" data-sitekey="{{ config('captcha.sitekey') }}"></div>
  • Http/Controllers/Auth/LoginController.php 新增

    1
    use Illuminate\Http\Request;

以及

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Validate the user login request.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required',
'password' => 'required',
'g-recaptcha-response' => 'required|captcha',
]);
}

  • 若要自訂 Validation 訊息可在 resources/lang/en/validation.php 新增

    1
    2
    3
    4
    5
    6
    'custom' => [
    'g-recaptcha-response' => [
    'required' => 'Please verify that you are not a robot.',
    'captcha' => 'Captcha error! try again later or contact site admin.',
    ],
    ],
  • captcha error 訊息可用以下方式來顯示

    1
    2
    3
    4
    5
    @if ($errors->has('g-recaptcha-response'))
    <span class="help-block">
    <strong>{{ $errors->first('g-recaptcha-response') }}</strong>
    </span>
    @endif